const DB = require('../core/DB')
const {
    Op
} = require('sequelize')

const {
    uPutToken,
    uMd5
} = require('../core/utils')

const Jwt = require('jsonwebtoken') // 解析 token
const {
    jwt_config
} = global.config
const secretKey = jwt_config.serect


class UserController {

    /* ------------------------- ok 用户令牌登录 -------------------------------*/
    async loginToken(ctx) {
        try {
            const { token } = ctx.request.body
            const decode = Jwt.verify(token, secretKey)

            const user = await DB.user.findByPk(decode.uid)
            let lastLoginAt = await user.get('updatedAt')
            // 更新登录时间
            user.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
            await user.save()

            const data = {
                user: {
                    userId: user.id,
                    name: user.name,
                    email: user.email,
                    admin: user.admin,
                    lastLoginAt
                },
                token: uPutToken(user.id)
            }
            global.Response.success(ctx, '登录成功', data)
        } catch (error) {
            global.Response.fail(ctx, '令牌失效')
        }

    }

    /* ------------------------- ok 用户登录 -------------------------------*/
    async loginUser(ctx) {
        const {
            email,
            password
        } = ctx.request.body

        const user = await DB.user.findOne({
            where: {
                email,
                password: uMd5(password)
            }
        })
        if (user) {
            let lastLoginAt = await user.get('updatedAt')
            // 更新登录时间
            user.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
            await user.save()


            const data = {
                user: {
                    userId: user.id,
                    name: user.name,
                    email: user.email,
                    admin: user.admin,
                    lastLoginAt
                },
                token: uPutToken(user.id)
            }
            global.Response.success(ctx, '登录成功', data)
        } else {
            global.Response.fail(ctx, '账号或密码错误')
        }
    }

    /* ------------------------- ok 匿名用户注册，无需邮箱验证 -------------------------------*/
    async registerAnonymity(ctx) {
        let {
            name = '匿名用户'
        } = ctx.request.body

        if (name == '' || name == undefined) name = '匿名用户'

        const user = await DB.user.create({
            name,
            email:'',
            password: uMd5(123456),// 初始密码
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        user.email = `@${user.get('id')}`
        await user.save()

        const data = {
            user: {
                userId: user.id,
                name: user.name,
                email: user.email,
            },
            token: uPutToken(user.id)
        }
        global.Response.success(ctx, '注册成功', data)
    }

    /* ------------------------- ok 用户注册 -------------------------------*/
    async registerUser(ctx) {
        const {
            email,
            password = 123456,
            name,
        } = ctx.request.body
        const same = await DB.user.findOne({
            where: {
                [Op.or]: [{
                    name
                },
                {
                    email
                }]
            }
        })
        if (same) {
            global.Response.exist(ctx, '该email或昵称已注册~')
        } else {
            const user = await DB.user.create({
                email,
                password: uMd5(password),
                name,
                createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
            })
            const data = {
                user: {
                    userId: user.id,
                    name: user.name,
                    email: user.email,
                },
                token: uPutToken(user.id)
            }
            global.Response.success(ctx, '注册成功', data)
        }
    }

    /* ------------------------- ok 获取指定用户信息 -------------------------------*/
    async getUserInfo(ctx) {
        const {
            id
        } = ctx.query
        const user = await DB.user.findByPk(id, {
            attributes: {
                exclude: ['password']
            }
        })
        if (user) {
            global.Response.success(ctx, undefined, user)
        } else {
            global.Response.null(ctx)
        }
    }

    /* ------------------------- ok 获取登录用户信息 -------------------------------*/
    async getLoginInfo(ctx) {
        const {
            email
        } = ctx.query
        const user = await DB.user.findOne({
            where: {
                email
            },
            attributes: {
                exclude: ['password']
            }
        })
        if (user) {
            const data = {
                user: {
                    userId: user.id,
                    name: user.name,
                    email: user.email,
                },
                token: uPutToken(user.id)
            }
            global.Response.success(ctx, email, data)
        } else {
            global.Response.null(ctx)
        }
    }


    /* ------------------------- ok 更新用户（密码） -------------------------------*/
    async updateUser(ctx) {
        const {
            id,
            name,
            password,
        } = ctx.request.body

        await DB.user.update({
            name,
            password: uMd5(password),
            updated_at: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        }, {
            where: {
                id,
            }
        }) // return [0] [1]

        global.Response.success(ctx, '更新成功')
    }



}

module.exports = new UserController